import json
import requests
import base64
import getpass
import sys
import qrcode_terminal
from selenium import webdriver
from time import sleep
from datetime import datetime
from io import BytesIO
from PIL import Image
from sys import version_info
from pyzbar.pyzbar import decode
from PIL import Image
from selenium.webdriver.remote.webelement import WebElement

debug = True
if len(sys.argv)==2 and str(sys.argv[1]) == "debug":
    debug = True

chrome_options = webdriver.ChromeOptions()
# 使用headless无界面浏览器模式
# chrome_options.add_argument("--proxy-server=http://218.75.158.153:3128")  # 代理ip
if not debug:
    chrome_options.add_argument('--headless')   # 增加无界面选项
chrome_options.add_argument('--disable-gpu')  # 如果不加这个选项，有时定位会出现问题
chrome_options.add_argument('--window-size=1920,1080')   # 设置窗口大小, 窗口大小会有影响
chrome_options.add_argument('--no-sandbox') #沙盒模式
# 启动浏览器，获取网页源代码
u = webdriver.Chrome(options=chrome_options,executable_path="./chromedriver")  # 地址为chromedriver.exe的地址


class User():
    def __init__(self):
        self.username = ''
        self.password = ''

    def get_username(self):
        return self.username

    def get_password(self):
        return self.password

    def set_username(self, value):
        self.username = value

    def set_password(self, value):
        self.password = value


class Login():
    def login(self,user):
        user.set_password(getpass.getpass("请输入密码："))

        url = "https://mooc.yinghuaonline.com/user/login"
        u.get(url)
        # 等待5秒
        sleep(2)
        # 选择学校
        u.find_element_by_id('schoolId').click()
        # value=15选的是中南林业科技大学涉外学院
        u.find_element_by_xpath('//select/option[@value="15"]').click()  
        # 账号
        u.find_element_by_id('username').send_keys(user.get_username())
        # 密码
        u.find_element_by_id('password').send_keys(user.get_password())
        # 登录
        u.find_element_by_xpath('//div[@class="inpbox"]/input[@value="登录"]').click()
        sleep(3)
        
        tool = Tools()

        #登录验证码
        try:
            u.find_element_by_class_name("layui-layer-btn0")
            u.find_element_by_class_name("layui-layer-btn0").click()
            yzm = u.find_element_by_id('codeImg').get_attribute('src')
            yzm = yzm.split('?')[0]
            if debug:
                print("登录需要验证码")
            img_path = user.get_username() + ".jpg"
            cookie = "token="+ u.get_cookies()[2]['value']
            tool.download(yzm,cookie,img_path)
            img = Image.open(img_path)
            code = tool.base64_api(uname='gksec', pwd='water123', img=img)
            u.find_element_by_id('code').send_keys(code)
            u.find_element_by_xpath('//div[@class="inpbox"]/input[@value="登录"]').click()
        except Exception as e:
            if debug:
                print(e)
                print("不需要验证码")

        sleep(3)
        try:
            tool.getwximage(u,user.get_username())
        except Exception as e:
            print(e)
            print("登陆失败")
            sys.exit(0)
        input("微信扫码后回车")
        sleep(5)
        cookie = u.get_cookies()[2]['value']
        # 停2秒等加载
        sleep(2)
        #若没改密码点一下
        try:
            u.find_element_by_class_name("layui-layer-btn0")
            u.find_element_by_class_name("layui-layer-btn0").click()
        except Exception as e:
            if debug:
                print(e)
        with open(user.get_username() + ".txt", 'wb') as f:
            f.write(cookie.encode())
        print("登录成功")

class Tools():
    def getwximage(self,user,username):
        codeImgPath = './%s-weixin.jpeg'%username
        url=u.find_element_by_class_name("qrcode").get_attribute('src')
        r = requests.get(url)
        with open(codeImgPath, 'wb') as f:
                #保存
                f.write(r.content)
        #将二维码绘制在控制台
        barcode_url = ''
        barcodes = decode(Image.open(codeImgPath))
        for barcode in barcodes:
            barcode_url = barcode.data.decode("utf-8")

        qrcode_terminal.draw(barcode_url)

    def base64_api(self,uname,pwd,img):
        img = img.convert('RGB')
        buffered = BytesIO()
        img.save(buffered, format="JPEG")
        if version_info.major >= 3:
            b64 = str(base64.b64encode(buffered.getvalue()), encoding='utf-8')
        else:
            b64 = str(base64.b64encode(buffered.getvalue()))
        data = {"username": uname, "password": pwd, "image": b64}
        result = json.loads(requests.post("http://api.ttshitu.com/base64", json=data).text)
        if result['success']:
            return result["data"]["result"]
        else:
            return result["message"]
        return ""

    def download(self,url,cookie,fileName):
        src = url

        header = {
            "Cookie": cookie,
        }

        r = requests.get(src, headers=header)

        with open(fileName, 'wb') as f:
            f.write(r.content)

        #print('下载完成')

    def play(self,cookie,username):
        # 静音
        u.find_element_by_xpath('//*[@id="videoContent"]/div/div[2]/div[17]/canvas').click()
        playing = True
        tool = Tools()
        while(playing):
            # 播放
            playBotton = u.find_element_by_xpath('//*[@id="videoContent"]/div/div[2]/div[1]')
            playBotton.click()
            sleep(2)

            try:
                yzm = u.find_element_by_xpath('//*[@id="layui-layer1"]/div[2]/div/div[2]/img[2]').get_attribute('src')
                #print(yzm)
                #yzm = "https://mooc.yinghuaonline.com/service/code/aa"
                img_path = username + ".jpg"
                tool.download(yzm, cookie, img_path)

                #sleep(3)
                img = Image.open(img_path)
                result = tool.base64_api(uname='gksec', pwd='water123', img=img)
                number = 1
                while 1:
                    xpath = '//*[@id="layui-layer' + str(number) +'"]/div[2]/div/div[2]/input[2]'
                    try:
                        u.find_element_by_xpath(xpath).send_keys(result)
                        break
                    except:
                        number += 1
                        continue
                #sleep(10)
                u.find_element_by_link_text("开始播放").click()
                sleep(2)
                #判断播放状态 //*[@id="videoContent"]/div/div[2]/div[1]
                playBotton = u.find_element_by_xpath('//*[@id="videoContent"]/div/div[2]/div[1]')
                if 'none' in playBotton.get_attribute('style'):
                    playing = False

            except Exception as e:
                if debug:
                    print(e)
                playing = False
                print("无验证码")

    def state(self,username,url,cookie):
        flag = 0
        n1 = 0
        n2 = 0
        while 1:
            u.get(url) #返回学习记录处
            sleep(0.2)
            total_catalog = u.find_element_by_xpath('//*[@id="searchForm"]/span/span[2]')
            print("已经学习 %s 个视频" % total_catalog.text)
            surplus_catalog = u.find_element_by_xpath('//*[@id="searchForm"]/span/span[3]')
            print("尚未学习 %s 个视频" % surplus_catalog.text)
            sleep(0.5)
            try:
                #未学完
                u.find_element_by_id('state').click()
                u.find_element_by_xpath('//*[@id="state"]/option[3]').click()
                u.find_element_by_xpath('//*[@id="searchForm"]/input[2]').click()
                sleep(0.5)
                href_list1 = u.find_elements_by_xpath('//*[@id="list"]/tbody/tr/td[1]/a')
                u.get(href_list1[n1].get_attribute('href'))
            except:
                flag = 1
            try:
                #未学
                if flag == 1:
                    u.find_element_by_id('state').click()
                    u.find_element_by_xpath('//*[@id="state"]/option[2]').click()
                    u.find_element_by_xpath('//*[@id="searchForm"]/input[2]').click()
                    sleep(0.5)
                    href_list2 = u.find_elements_by_xpath('//*[@id="list"]/tbody/tr/td[1]/a')
                    u.get(href_list2[n2].get_attribute('href'))
            except:
                if(int(surplus_catalog.text) == 0):
                    break
            # 播放
            tool = Tools()
            tool.play(cookie,username)

            print("开始时间是%s" % datetime.now())
            # 每个视频停留
            time = u.find_element_by_xpath('//*[@id="videoContent"]/div/div[2]/div[8]')
            time = str(time.text)
            if time[8:10] == '00' and time[11:13] == '00':
                if flag == 0:
                    n1 += 1
                else:
                    n2 += 1
            sleep(int(time[8:10]) * 60 + 60)
            print("结束时间是%s" % datetime.now())
                
        # 退出
        print("完成")


if __name__ == "__main__":
    username = input("请输入账号：")
    text_list = input("请输入需要刷网课的编号：")
    try:
        f = open('./' + username + '.txt')
        cookie = f.read()
    except:
        print('该账号还没有登录，请登录')
        user = User()
        user.set_username(username)
        login = Login()
        login.login(user)
        f = open('./' + username + '.txt')
        cookie = f.read()
    tool = Tools()
    token = {'name': 'token', 'value': cookie}
    cookied = 'token=' + cookie
    u.get('https://mooc.yinghuaonline.com/user/login')
    sleep(2)
    u.add_cookie(token)
    u.get('https://mooc.yinghuaonline.com/user/')

    course_list = u.find_elements_by_link_text("学习记录")
    for i in text_list:
        while 1:
            try:
                tool.state(username, course_list[int(i)-1].get_attribute('href'), cookied)
                break
            except:
                continue
